import { store } from "@/store";
import common from "@/utils";
import type { UserInfo } from "@/types/user";

export const useUserStore = defineStore("user", () => {
	const userInfo = ref<UserInfo>(
		common.getStorage("userInfo") || {
			avatar_url: "",
			nickname: ""
		}
	);
	const token = ref(common.getStorage("accessToken"));

	/**
	 * 设置userInfo
	 */
	function setUserInfo(info: UserInfo) {
		userInfo.value = info;
		common.setStorage("userInfo", userInfo.value);
	}

	/**
	 * 移除token
	 * @returns Promise
	 */
	function resetToken() {
		return new Promise<void>((resolve) => {
			token.value = "";
			common.removeStorage("accessToken");
			resolve();
		});
	}

	return {
		token,
		resetToken,
		userInfo,
		setUserInfo
	};
});

/**
 * 非setup
 * @returns useUserStore
 * */
export function useUserStoreHook() {
	return useUserStore(store);
}
